<?php
/**
 * 解析后的模板文件路径
 * @param $file string
 * @return string
 */
function template($file = '') {
	global $_g,$_config,$_mod,$_do,$_template;
	
	if (empty($file)) {
		$name = $_mod.'/'.$_do.'.htm';
	} else {
		$tmp = explode('/', $file);
		$name = count($tmp)==2 ? $file : $_mod.'/'.$file.'.htm';
	}

	return $_template->getfile($name);
}

/**
 * 分页
 * @param $total int
 * @param $tpp int
 * @param $page int
 * @param $url string
 * @return string
 */
function multi($total, $tpp, $page, $url) {
	$length = 10;
	$backStr = '';
	$anchor = '';
	
	//考虑锚点
	if (strpos($url, '#') !== FALSE) {
		$tmp = explode('#', $url);
		$url = $tmp[0];
		$anchor = '#'.$tmp[1];
	}
	//考虑是否有参数
	$url .= strpos($url, '?') !== FALSE ? '&amp;' : '?';
	
	if ($total > $tpp) {
		$offset = floor($length * 0.5);#偏差
		$pages = ceil($total / $tpp);#总页数
		
		//范围
		if ($pages < $length) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $page - $offset;
			$to = $from + $length - 1;
			
			if ($from < 1) {
				$from = 1;
				$to = min($length, $pages);
			} elseif ($to > $pages) {
				$to = $pages;
				$from = $pages - $length + 1;
			}
		}
		
		//分页html
		$backStr  = ($page>1)?'<a href="'.$url.'page='.($page-1).$anchor.'" class="prev">&lsaquo;&lsaquo;</a>':'';
		$backStr .= ($page-$offset>1) ? '<a href="'.$url.'page=1'.$anchor.'" class="first">1 ...</a>':'';
		for ($i = $from; $i <= $to; $i++) {
			$backStr .= ($i==$page)?'<strong>'.$i.'</strong>':'<a href="'.$url.'page='.$i.$anchor.'">'.$i.'</a>';
		}
		$backStr .= ($to<$pages)?'<a href="'.$url.'page='.$pages.$anchor.'" class="last">... '.$pages.'</a>':'';
		$backStr .= ($page<$pages)?'<a href="'.$url.'page='.($page+1).$anchor.'" class="nxt">&rsaquo;&rsaquo;</a>':'';
		
		$backStr = $backStr ? '<div class="pg"><em>&nbsp;'.$total.'&nbsp;</em>'.$backStr.'</div>' : '';
		//--end
	}
	
	return $backStr;
}

/**
 * 消息提示
 * @param $url string
 * @param $message string
 * @param $type string
 */
function jump($url, $message='', $type='header', $result='') {
	global $template;
	
	//跳转方式
	$types = array('header', 'timeout');
	$type = in_array($type, $types) ? $type : 'header';
	//结果
	$results = array('succeed', 'error');
	$result = in_array($result, $results) ? $result : 'succeed';
	
	switch ($type) {
		case 'header':
			header("HTTP/1.1 301 Moved Permanently");
			header("location: $url");
			break;
		
		case 'timeout':
			$jsHtml = '<script type="text/javascript" reload="1">setTimeout("window.location.href=\''.$url.'\';", 3000);</script>';
			include template('common/showmessage.htm');
			break;
	}
	die;
}

/**
 * 模拟POST提交
 * @param $url string
 * @return string
 * @param $data array
 */
function simulatePost($url, $data) {
	$str = '';
	foreach ($data as $key=>$value) {
		$str .= $key."=".urlencode($value)."&";
	}
	$str = rtrim($str, "&");
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$result = curl_exec($ch);
	curl_close ($ch);
	
	return $result;
}

/**
 * 模拟GET获取数据
 * @param $url string
 * @return string
 */
function simulateGet($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$result = curl_exec($ch);
	curl_close ($ch);
	
	return $result;
}

/**
 * 表单Hash
 * @param string $add //特殊数据
 * @return string
 */
function formHash($add = '') {
	$uid = empty($_SESSION['userInfo']['id']) ? 0 : $_SESSION['userInfo']['id'];
	$email = empty($_SESSION['userInfo']['email']) ? '' : $_SESSION['userInfo']['email'];
	$timestamp = time();
	return substr(md5(substr($timestamp, 0, -7).$uid.$email.AUTHKEY.$add), 8, 8);
}

/**
 * 将路径修正为适合操作系统的形式
 * @param  string $path 路径名称
 * @return string
 */
function trimPath($path) {
	return str_replace(array('/', '\\', '//', '\\\\'), DIR_SEP, $path);
}
    
/**
 * 创建文件夹
 * @param string $fileDir
 * @return bool
 */
function createDir($fileDir) {
	if (!empty($fileDir)) {
        $dirs = explode(DIR_SEP, trimPath($fileDir));
        $tmp = '';
        foreach ($dirs as $dir) {
            $tmp .= $dir . DIR_SEP;
            if (!file_exists($tmp) && !@mkdir($tmp, 0777))
                return false;
        }
	}
    return true;
}

/**
 * 获得格式化的时间
 * @param string $time
 * @param int $type
 * @return string
 */
function getTimeStr($time, $type){
	if ($type == 1) {
		$tmp = date("Y年m月d日", $time);
		$w = date('w', $time);
		switch ($w)	{
			case 0: $tmp .= ' 星期日'; break;
			case 1: $tmp .= ' 星期一'; break;
			case 2: $tmp .= ' 星期二'; break;
			case 3: $tmp .= ' 星期三'; break;
			case 4: $tmp .= ' 星期四'; break;
			case 5: $tmp .= ' 星期五'; break;
			case 6: $tmp .= ' 星期六'; break;			
		}
		return $tmp;
	}
}

/**
 * 获取文件的真实类型
 * @param string $file
 * @return string
 */
function fileRealType($file) {
	if (is_file($file) && file_exists($file)) {
		$p = fopen($file, 'rb');
		$bin = fread($p, 2);#读文件的前两个字节
		fclose($p);
		
		$tmp = unpack("C2chars", $bin);
		$typeCode = intval($tmp['chars1'].$tmp['chars2']);
		
		switch ($typeCode) {
			case 7790: $back = 'exe'; break;
			case 7784: $back = 'midi'; break;
			case 8297: $back = 'rar'; break;
			case 255216: $back = 'jpg'; break;
			case 7173: $back = 'gif'; break;
			case 6677: $back = 'bmp'; break;
			case 13780: $back = 'png'; break;
			default: $back = 'unknown'; break;
		}
		return $back;
	} else {
		return 'unknown';
	}
}

/**
 * 图片的输出头类型
 * @param string $type
 * @param string
 */
function headerImgType($type) {
	switch ($type) {
		case 'jpg': $back='Content-type: image/jpeg'; break;
		case 'gif': $back='Content-type: image/gif'; break;
		case 'bmp': $back='Content-type: image/bmp'; break;
		case 'png': $back='Content-type: image/png'; break;
		default: $back='Content-type: application/octet-stream'; break;
	};
	return $back;
}

/**
 * 获取当前页面url
 * @return string
 */
function getUrl() {
	$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
	return $url;
}

/**
 * dz经典加解密函数
 * 来源：Discuz! 7.0
 * 依赖性：可独立提取使用
 *
 * @param string $string 要加密/解密的字符串
 * @param string $operation 操作类型，可选为'DECODE'（默认）或者'ENCODE'
 * @param string $key 密钥，必须传入，否则将中断php脚本运行。
 * @param int $expiry 有效期
 * @return string
 */
function authcode($string, $operation = 'DECODE', $key, $expiry = 0) {
	
	$ckey_length = 4;	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥
	
	//取消UC_KEY，改为必须传入$key才能运行
	if(empty($key)){
		exit('PARAM $key IS EMPTY! ENCODE/DECODE IS NOT WORK!');
	}else{
		$key = md5($key);
	}
	
	
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	
	$result = '';
	$box = range(0, 255);
	
	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

/**
 * 返回文件的扩展名
 * 来源：Discuz!
 * 依赖性：可独立提取使用
 * 
 * @param string $filename 文件名
 * @return string
 */
function fileExt($filename) {
	return trim(substr(strrchr($filename, '.'), 1, 10));
}

/**
 * 数组赋值
 * @param array $arr1
 * @param array $arr2
 * @param string $type //add edit
 * @return array
 */
function assignArray($arr1, $arr2, $type='add') {
	$back = array();
	foreach ($arr1 as $key=>$value) {
		if (isset($arr2[$key])) {
			$back[$key] = $arr2[$key];
		} else {
			if ($type == 'add') {
				$back[$key] = $value;
			}
		}
	}
	return $back;
}

function cAddslashes($arr) {
	foreach ($arr as $key=>$value) {
		$arr[$key] = addslashes($value);
	}
	return $arr;
}

/**
 * 生成缩略图
 * @param string $srcName
 * @param int $newWidth
 * @param int $newHeight
 * @param string $newName
 */
function resizeImg($srcName, $newWidth, $newHeight, $newName='') {
	
	//图片名称
	if ($newName == '') {
		$nameArr = explode('.', $srcName);
		$expName = array_pop($nameArr);
		$expName = $newWidth.'x'.$newHeight.'.'.$expName;
		array_push($nameArr, $expName);
		$newName = implode('.', $nameArr);
	}
	
	//读取图片信息
	$info = '';
	$data = getimagesize($srcName, $info);
	
	switch ($data[2]) {
		case 1:
			if (function_exists("imagecreatefromgif")) {
				$im = imagecreatefromgif($srcName);
			} else {
				die('你的GD库不能使用GIF格式的图片');
			}
			break;
		case 2:
			if (function_exists("imagecreatefromjpeg")) {
				$im = imagecreatefromjpeg($srcName);
			} else {
				die('你的GD库不能使用jpeg格式的图片');
			}
			break;
		case 3:
			$im = imagecreatefrompng($srcName);
			break;
		default:
			return false;
		break;
	}	
	$srcW = imagesx($im);#宽度
	$srcH = imagesy($im);#高度
	
	//缩放后的尺寸
	$newRate = $newWidth / $newHeight;
	$srcRate = $srcW / $srcH;
	if ($newRate <= $srcRate) {
		$toW = $newWidth;
		$toH = $toW * ($srcH / $srcW);
	} else {
		$toH = $newHeight;
		$toW = $toH * ($srcW / $srcH);
	}
	
	//开始缩放
	if ($srcW > $newWidth || $srcH > $newHeight) {
		if (function_exists("imagecreatetruecolor")) {
			@$ni = imagecreatetruecolor($toW, $toH);
			if ($ni) {
				imagecopyresampled($ni, $im, 0, 0, 0, 0, $toW, $toH, $srcW, $srcH);
			} else {
				$ni = imagecreate($toW, $toH);
				imagecopyresampled($ni, $im, 0, 0, 0, 0, $toW, $toH, $srcW, $srcH);
			}
		} else {
			$ni = imagecreate($toW, $toH);
			imagecopyresampled($ni, $im, 0, 0, 0, 0, $toW, $toH, $srcW, $srcH);			
		}
		
		if (function_exists("imagejpeg")) {
			imagejpeg($ni, $newName);
		} else {
			imagepng($ni, $newName);
		}
		
		imagedestroy($ni);
	} else {
		copy($srcName, $newName);
	}
	
	imagedestroy($im);
}
?>